﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kaiser.Domains;
using Kaiser.Extensions;
using Kaiser.MvcBase.Models;

namespace Kaiser.MvcBase.ControllerBase
{
    public enum UpdateWay
    {
        None, DelUpdate
    }

    public class ManageController : PortalBaseController
    {
        protected virtual string CheckModelState()
        {
            var errList = ModelState.Values.Where(x => x.Errors.Count > 0).Select(x => x.Errors).ToList();
            var msg = errList.Select(x =>
            {
                var firstOrDefault = x.FirstOrDefault();
                return firstOrDefault != null ? firstOrDefault.ErrorMessage : null;
            }).ToList().StringJoin(",");

            return msg;
        }
    }

    public abstract class ManageController<T, TSearch> : ManageController where T : EntityBase<T>, new()
    {
        protected String EditPage = "Edit";
        protected String CreatePage = "Edit";
        protected String ScanPage = "Scan";
        protected String ListPage = "List";

        protected UpdateWay UpdateWay = UpdateWay.None;

        protected virtual T GetModel(long id)
        {
            return EntityBase<T>.Get(id);
        }

        #region 创建

        protected virtual void CreateModel(T model)
        {
            EntityBase<T>.Add(model);
        }

        public virtual ActionResult Create()
        {
            var model = new T();

            return View(CreatePage, model);
        }

        [HttpPost]
        [ValidateInput(false)]

        public virtual ActionResult Create(T model)
        {
            var result = new JsonReturnMessages();
            try
            {
                if (ModelState.IsValid)
                {
                    CreateModel(model);
                    result.success = true;
                    result.msg = "新增成功！";
                }
                else
                {
                    result.success = false;
                    result.msg = CheckModelState();
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }

            return View(CreatePage, model);
        }
        #endregion

        #region 保存

        protected virtual void ModifyModel(long id)
        {
            var oldModel = GetModel(id);
            TryUpdateModel(oldModel);
            if (ModelState.IsValid)
            {
                ModifyModel(oldModel);
            }
            else
            {
                CheckModelState();
            }
        }

        protected virtual void ModifyModel(T oldModel)
        {
            EntityBase<T>.Edit(oldModel);
        }

        public virtual ActionResult Scan(long id)
        {
            var model = GetModel(id);

            return View(ScanPage, model);
        }


        public virtual ActionResult Edit(long id)
        {
            var model = GetModel(id);

            return View(EditPage, model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Edit(long id, FormCollection form)
        {
            var result = new JsonReturnMessages();
            try
            {
                if (ModelState.IsValid)
                {
                    ModifyModel(id);
                    result.success = true;
                    result.msg = "保存成功！";
                }
                else
                {
                    result.success = false;
                    result.msg = this.CheckModelState();
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }
            return Json(result);
        }

        #endregion

        #region 删除

        protected virtual void RemoveModel(long id)
        {
            EntityBase<T>.Remove(id);
        }


        public virtual ActionResult Remove(long id)
        {
            var result = new JsonReturnMessages();
            try
            {

                RemoveModel(id);
                result.success = true;
                result.msg = "删除成功！";
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;

            }
            return Json(result);
        }

        //protected string GetBackUrl()
        //{
        //    if (!string.IsNullOrWhiteSpace(Request["ReturnUrl"]))
        //    {
        //        return Request["ReturnUrl"];
        //    }
        //    else if (Request.UrlReferrer != null)
        //    {
        //        return Request.UrlReferrer.ToString();
        //    }
        //    else
        //    {
        //        return ListPage;
        //    }
        //}

        #endregion

        #region 编辑或创建

        public virtual ActionResult Save(long id)
        {
            var model = GetModel(id) ?? new T();

            return View(EditPage, model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public virtual ActionResult Save(long id, FormCollection form)
        {
            var result = new JsonReturnMessages();
            try
            {

                if (UpdateWay == UpdateWay.DelUpdate)
                {
                    var model = new T();
                    TryUpdateModel(model);
                    if (ModelState.IsValid)
                    {
                        if (id != 0)
                        {
                            RemoveModel(id);
                        }

                        CreateModel(model);
                        result.success = true;
                        result.msg = "保存成功！";
                    }
                    else
                    {
                        result.success = false;
                        result.msg = this.CheckModelState();
                    }
                }
                else
                {
                    var model = GetModel(id);
                    if (model == null)
                    {
                        model = new T();
                        TryUpdateModel(model);
                        if (ModelState.IsValid)
                        {
                            CreateModel(model);
                            result.success = true;
                            result.msg = "保存成功！";
                        }
                        else
                        {
                            result.success = false;
                            result.msg = this.CheckModelState();
                        }
                    }
                    else
                    {
                        TryUpdateModel(model);
                        if (ModelState.IsValid)
                        {
                            ModifyModel(model);
                            result.success = true;
                            result.msg = "保存成功！";
                        }
                        else
                        {
                            result.success = false;
                            result.msg = this.CheckModelState();
                        }
                    }
    
                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }
            return Json(result);
        }

        #endregion

        #region 列表


        public virtual ActionResult List(TSearch page)
        {
            return View(ListPage, page);
        }

        #endregion



    }
}
